﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Api.Hub.Constraints
{
    public class Int32RangeConstraint : System.Web.Http.Routing.IHttpRouteConstraint
    {
        public Int32RangeConstraint(int minValue, int maxValue)
        {
            this.MinValue = minValue;
            this.MaxValue = maxValue;
        }

        private int MinValue;

        private int MaxValue;

        public bool Match(System.Net.Http.HttpRequestMessage request, System.Web.Http.Routing.IHttpRoute route, string parameterName, IDictionary<string, object> values, System.Web.Http.Routing.HttpRouteDirection routeDirection)
        {
            try
            {
                if (!values.Any())
                {
                    return false;
                }

                object val = 0;
                if (values.TryGetValue(parameterName, out val) && !string.IsNullOrWhiteSpace(val.ToString()))
                {
                    var int_val = Convert.ToInt32(val);

                    if (int_val >= this.MinValue && int_val <= this.MaxValue)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
